package com.yhans.serviceImpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yhans.constant.RedisConstant;
import com.yhans.dao.CheckGroupDao;
import com.yhans.dao.CheckItemDao;
import com.yhans.dao.SetmealDao;
import com.yhans.entity.PageResult;
import com.yhans.entity.QueryPageBean;
import com.yhans.pojo.CheckGroup;
import com.yhans.pojo.CheckItem;
import com.yhans.pojo.Setmeal;
import com.yhans.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private CheckGroupDao checkGroupDao;

    @Autowired
    private CheckItemDao checkItemDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    @Value("${in_put_path}")
    private String intPutPath;
    //新增套餐
    public void add(Setmeal setmeal, Integer[] checkgroupIds) throws IOException {

        //保存套餐数据
        setmealDao.add(setmeal);
        if(checkgroupIds != null && checkgroupIds.length > 0){
            //绑定套餐和检查组的多对多关系
            //保存套餐表和检查组的中间关系表
            setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }
        //将图片名称保存到Redis集合中
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);

        //生成套餐后需要重新生成静态页面(套餐列表页面,套餐详情页面)
        generateMobileStaticHtml();
    }

    //绑定套餐和检查组多对多关系(已有数据就覆盖数据)
    public void setSetmealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {

        for (int i = 0; i < checkgroupIds.length; i++) {
            HashMap<String,Integer> map= new HashMap<>();
            map.put("setmeal_id",setmealId);
            //put一次 数据库插入一次
            map.put("checkgroup_id",checkgroupIds[i]);

            setmealDao.setSetmealAndCheckGroup(map);
        }
    }


    //生成静态页面
    public void generateMobileStaticHtml() throws IOException {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }
    //生成套餐列表静态页面(一个)
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) throws IOException {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);
    }
    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) throws IOException {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal", this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html",
                    dataMap);
        }
    }
    //用于生成静态页面
    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) throws IOException {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        configuration.setDirectoryForTemplateLoading(new File(intPutPath));
        Writer out = null;
        try {
            // 加载模版文件
            Template template = configuration.getTemplate(templateName);
            // 生成数据
            File docFile = new File(outPutPath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            // 输出文件
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }





    //套餐分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) {

        //获取页面,当前页和查询条件
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        if (queryString!=null&&queryString.length()!=0){
            currentPage=1;
        }
        //完成分页查询,基于mybatis框架提供的分页助手
        PageHelper.startPage(currentPage,pageSize);

        Page<Setmeal> page = setmealDao.pageQuery(queryString);
        long total = page.getTotal();
        List<Setmeal> result = page.getResult();

        return new PageResult(total,result);
    }

    //编辑回显套餐111111111111111111
    public Setmeal findById(Integer id) {

        return setmealDao.findById(id);
    }

    //查询与套餐关联的检查组
    public ArrayList<Integer> findCheckGroupIdsBySetmealId(Integer id) {
        return setmealDao.findCheckGroupIdsBySetmealId(id);
    }

    //编辑修改套餐和关联的检查组信息
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) throws IOException {

        //1.更新套餐信息
        setmealDao.edit(setmeal);
        //将图片名称保存到Redis集合中
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);

        //2.删除中间表的信息
        setmealDao.deleteAssociation(setmeal.getId());
        //3.向中间表插入关联信息
        setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);

        //生成套餐后需要重新生成静态页面(套餐列表页面,套餐详情页面)
        generateMobileStaticHtml();

    }

    //删除套餐和中间表的信息
    public void delete(Integer id) throws IOException {


        //1.删除套餐相关的中间表
        setmealDao.deleteAssociation(id);
        //2.删除套餐
        setmealDao.delete(id);
        //生成套餐后需要重新生成静态页面(套餐列表页面,套餐详情页面)
        generateMobileStaticHtml();

    }

    //查询全部套餐信息
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    //返回id对应的套餐 的 检查组和检查项222222222222222222222222222
    public Setmeal testFindById(Integer id) {

        //查询当前的套餐信息(以及要返回的数据)
        Setmeal setmeal = setmealDao.findById(id);
        //查询 套餐-检查组 所对应的中间关系表的 检查组id
        ArrayList<Integer> checkGroupIdsBySetmealId = setmealDao.findCheckGroupIdsBySetmealId(id);
        
        //获取套餐id所对应的检查组信息
        ArrayList<CheckGroup> checkGroups = new ArrayList<>();
        for (Integer checkGroupId : checkGroupIdsBySetmealId) {
            
            CheckGroup checkGroup = checkGroupDao.findById(checkGroupId);
            
            //查询 检查组-检查项 所对应的中间关系表的 检查项id
            List<Integer> checkItemIdsByCheckGroupId = checkGroupDao.findCheckItemIdsByCheckGroupId(checkGroupId);
            //获取检查组id所对应的检查项信息
            ArrayList<CheckItem> checkItems = new ArrayList<>();
            for (Integer checkItemId : checkItemIdsByCheckGroupId) {
                CheckItem checkItem = checkItemDao.findById(checkItemId);
                checkItems.add(checkItem);
            }
            checkGroup.setCheckItems(checkItems);
            checkGroups.add(checkGroup);
            
        }

        setmeal.setCheckGroups(checkGroups);
        return setmeal;

    }
    //查询套餐名称和预约数量

    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }
}
